package com.cat.simulation;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/cyclically-rotating-a-grid/description/?envType=problem-list-v2&envId=simulation
 * @create 2025/8/29 14:53
 * @since JDK17
 */

public class Solution06 {
    static int[][] dire = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    public int[][] rotateGrid(int[][] grid, int k) {
        int n = grid.length, m = grid[0].length, cnt = Math.min(n, m) / 2;
        List<Integer> list = new ArrayList<>();
        for (int l = 0, x = 0, y = 0; l < cnt; l++, y++) {
            list.clear();
            for (; y < m - l; y++) {
                list.add(grid[x][y]);
            }
            for (y--, x++; x < n - l; x++) {
                list.add(grid[x][y]);
            }
            for (x++, y--; y >= l; y--) {
                list.add(grid[x][y]);
            }
            for (y++, x--; x > l; x--) {
                list.add(grid[x][y]);
            }
            int t = k % list.size();
            for (int i = 0, temp; i < t; i++) {
                temp = list.get(0);
                for (int j = 0; j < list.size() - 1; j++) {
                    list.set(j, list.get(j + 1));
                }
                list.set(list.size() - 1, temp);
            }
            x = l;
            y = l;
            int c = 0;
            for (; y < m - l; y++) {
                grid[x][y] = list.get(c++);
            }
            for (y--, x++; x < n - l; x++) {
                grid[x][y] = list.get(c++);
            }
            for (x++, y--; y >= l; y--) {
                grid[x][y] = list.get(c++);
            }
            for (y++, x--; x > l; x--) {
                grid[x][y] = list.get(c++);
            }
            System.out.println("list.size() = " + list.size());
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.print(grid[i][j] + " ");
            }
            System.out.println();
        }

        return grid;
    }
}
